package com.cqupt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cqupt.mapper.HostMapper;
import com.cqupt.pojo.Host;
import com.cqupt.pojo.Interface;
import com.cqupt.service.DashBoardService;
import com.cqupt.service.HostService;
import com.cqupt.service.ItemService;
import com.cqupt.utils.APIUtils;
import com.cqupt.utils.DateUtils;
import com.cqupt.utils.RegularMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class HostServiceImpl implements HostService {
    @Autowired
    private HostMapper hostMapper;

    @Autowired
    private DashBoardService dashBoardService;
    /**
     * 获取所有主机组
     * @param token 令牌（String）
     * @return
     */
    public List<Map<String, Object>> getGroups(final String token) {
        // 请求参数封装
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "hostgroup.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                List<String> output = new ArrayList<>();
                output.add("groupid");
                output.add("name");
                put("output", output);
                put("filter", new HashMap<String, Object>() {{
                    put("name", "");
                }});
            }});
        }};

        // 请求发送
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>) responseMap.get("result");
    }

    /**
     * 获取所有主机的所有信息
     * @param token
     * @param type
     * @param avail
     * @return
     */
    public List<Map<String, Object>> getAllHosts(final String token,final String type,final String avail) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 2);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                // 过滤返回结果信息
                List<String> output = new ArrayList<>();
                output.add("hostid");
                output.add("description");
                output.add("host");
                output.add("status");
                output.add("available");
                output.add("ipmi_available");
                output.add("jmx_available");
                output.add("snmp_available");
                put("output", output);
                put("filter", new HashMap<String, Object>() {{
                    put("host", "");
                    if (type.equals("1")&& avail.equals("1")){//服务器可用
                        put("available","1");
                    }else if (type.equals("1") && avail.equals("2")){//服务器不可用
                        put("available","2");
                    }else if (type.equals("1") && avail.equals("0") ){//服务器（可用，不可用）
                        put("available", new String[]{"1", "2"});
                    }else if (type.equals("2")  && avail.equals("1")){//网络设备可用
                        put("snmp_available","1");
                    }else if (type.equals("2") && avail.equals("2")){//网络设备不可用
                        put("snmp_available","2");
                    }else if (type.equals("2") && avail.equals("0") ){//网络设备（可用，不可用）
                        put("snmp_available",new String[]{"1","2"});
                    }else if (type.equals("0") && avail.equals("1")){//可用
                        put("available","1");
                        put("snmp_available","1");
                    }else if (type.equals("0") && avail.equals("2") ){//不可用
                        put("available","2");
                        put("snmp_available","2");
                    }else {
                    }
                }});
                put("searchByAny",true);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>) responseMap.get("result");
    }

    /**
     * 获取设备运行状态为“可用”的设备
     * @param token 令牌
     * @return
     */
    @Override
    public List<Map<String, Object>> getAvailableAllHosts(final String token) {
        HostServiceImpl hostService = new HostServiceImpl();
        // 请求获取所有设备
        List<Map<String, Object>> hosts = hostService.getAllHosts(token,"0","0");
        List<Map<String,Object>> availhosts = new ArrayList<>();
        for (int i=0;i<hosts.size();i++){
            // 依据四种设备类型分别过滤出可用的设备，其available状态为“1”
            if ("1".equals(hosts.get(i).get("available")) || "1".equals(hosts.get(i).get("ipmi_available")) || "1".equals(hosts.get(i).get("jmx_available"))||"1".equals(hosts.get(i).get("snmp_available"))){
                availhosts.add(hosts.get(i));
            }
        }
        return availhosts;
    }

    /**
     * 获取设备运行状态为“未知-0”或“失效-2”的设备
     * @param token 令牌
     * @return
     */
    @Override
    public List<Map<String, Object>> getUnAvailableAllHosts(final String token) {
        HostServiceImpl hostService = new HostServiceImpl();
        // 请求获取所有设备
        List<Map<String, Object>> hosts = hostService.getAllHosts(token,"0","0");
        List<Map<String,Object>> unavailhosts = new ArrayList<>();
        for (int i=0;i<hosts.size();i++){
            // 若设备运行状态为“可用”则跳出本次循环，否则添加保存
            if ("1".equals(hosts.get(i).get("available")) || "1".equals(hosts.get(i).get("ipmi_available")) || "1".equals(hosts.get(i).get("jmx_available"))||"1".equals(hosts.get(i).get("snmp_available"))){
                continue;
            }
            unavailhosts.add(hosts.get(i));
        }
        return unavailhosts;
    }

    /**
     * 对agent接口类型的设备（普通服务器），过滤出其中运行状态为“失效-2”和“可用-1”的
     * @param token 令牌
     * @return
     */
    @Override
    public List<Map<String, Object>> getServerAllHosts(String token) {
        HostServiceImpl hostService = new HostServiceImpl();
        // 请求获取所有设备
        List<Map<String, Object>> hosts = hostService.getAllHosts(token,"0","0");
        List<Map<String,Object>> serverhosts = new ArrayList<>();
        for (int i=0;i<hosts.size();i++){
            // 依据参数过滤
            if ("1".equals(hosts.get(i).get("available")) || "2".equals(hosts.get(i).get("available"))){
                serverhosts.add(hosts.get(i));
            }

        }
        return serverhosts;
    }

    /**
     * 对agent接口类型的设备（普通服务器），过滤出其中运行状态为“未知-0”的
     * @param token 令牌
     * @return
     */
    @Override
    public List<Map<String, Object>> getOtherAllHosts(String token) {
        HostServiceImpl hostService = new HostServiceImpl();
        List<Map<String, Object>> hosts = hostService.getAllHosts(token,"0","0");
        List<Map<String,Object>> otherhosts = new ArrayList<>();
        for (int i=0;i<hosts.size();i++){
            if ("1".equals(hosts.get(i).get("available")) || "2".equals(hosts.get(i).get("available"))){
                continue;
            }
            otherhosts.add(hosts.get(i));
        }
        return otherhosts;
    }

    /**
     * 获取某个主机的信息(byHostid)
     * @param token 令牌（String）
     * @param hostid 主机id(String)
     * @return
     */
    @Override
    public List<Map<String, Object>> getHostByHostid(final String token, final String hostid) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 2);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                put("hostids", hostid);

                // 封装过滤返回信息
                List<String> output = new ArrayList<>();
                output.add("hostid");
                output.add("description");
                output.add("host");
                put("output", output);

                // 封装返回的模板信息
                List<String> templates = new ArrayList<>();
                templates.add("groupid");
                put("selectParentTemplates", templates);
                List<String> groups = new ArrayList<>();
                groups.add("templateid");
                put("selectGroups", groups);
                put("selectInterfaces", "extend");
            }});
        }};

        // 请求发送
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>) responseMap.get("result");
    }

    /**
     * 获取与指定主机id相关联的所有监控项的个数
     * @param token 令牌
     * @param hostids 主机id（List<String>）
     * @return
     */
    public Map<String, Integer> getItemCount(final String token, final List<String> hostids) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "item.get");// 请求内容为：监控项获取
            put("id", 4);
            put("auth", token);
            List<String> outputs = new ArrayList<>();
            outputs.add("hostid");
            outputs.add("itemid");
            put("params", new HashMap<String, Object>() {{
                put("output", outputs);
                put("hostids", hostids);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map> result = (List<Map>) responseMap.get("result");
        Map<String, Integer> hostAndItemCount = new HashMap<>();
        int count = 0;
        //获取第一个hostid
        if (result.size() != 0) {
            String temp = (String) result.get(0).get("hostid");
            for (Map map : result) {
                //通过查询hostid重复的值得出该hostid中的item数
                if (temp.equals((String) map.get("hostid"))) {
                    count++;
                } else {
                    hostAndItemCount.put(temp, count);
                    temp = (String) map.get("hostid");
                    count = 1;
                }
            }
            hostAndItemCount.put(temp, count);
        }
        //没有监控项的host将item数设为0
        for (String hostid : hostids) {
            if (hostAndItemCount.get(hostid) == null) {
                hostAndItemCount.put(hostid, 0);
            }
        }
        return hostAndItemCount;
    }

    /**
     * 获取与指定主机id相关联的所有触发器的个数
     * @param token
     * @param hostids
     * @return
     */
    public Integer getTriggerCount(final String token, final String hostids) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "trigger.get");
            put("id", 5);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                put("countOutput", true);
                put("hostids", hostids);// 指定要返回的主机对象的触发器
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        Object result = responseMap.get("result");

        // 数量统计
        int count = 0;
        if (result != null)
            count = Integer.parseInt(result.toString());
        return count;
    }

    /**
     * 获取所有与指定主机id相关联的所有模板的所有信息
     * @param token 令牌
     * @return
     */
    public List<Map<String, Object>> getTemplates(final String token) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "template.get");
            put("id", 7);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                List<String> output = new ArrayList<>();
                output.add("templateid");
                output.add("host");
                put("output", output);
                put("selectHosts", "");
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>) responseMap.get("result");
    }

    /**
     * 添加主机
     * @param token 令牌
     * @param host  要创建的主机名（必须）
     * @param inter 主机连接的接口（必须）
     * @return 响应结果
     */
    public Map<String, Object> addHost(final String token, final String host, final String description, final Interface inter, final String systemType,final HashMap<String,String> inventory) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.create");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                //主机名称
                put("host", host);
                //主机描述
                if (description != null) {
                    put("description", description);
                }else {
                    put("description", "");
                }

//                if(1 == inter.getType()){
//                    put("description", description + "\n" +"<agent>");
//                }else if(2 == inter.getType()){
//                    put("description", description + "\n" +"<switch>");
//                }else if(3 == inter.getType()){
//                    put("description", description + "\n" +"<firewall>");
//                }else if(4 == inter.getType()){
//                    put("description", description + "\n" +"<single_gate>");
//                }
                //添加普通主机
                put("flags", 0);
                //主机所连接的接口
                put("interfaces", new HashMap<String, Object>() {{
//                    put("type", inter.getType());
                    if (1 != inter.getType()) {
                        put("type", "2");
                    }else{
                        put("type", inter.getType());
                    }
                    put("main", inter.getMain());
                    put("useip", inter.getUseip());
                    put("ip", inter.getIp());
                    put("dns", inter.getDns());
                    put("port", inter.getPort());
                    if (1 != inter.getType()) {
                        put("details", new HashMap<String, Object>() {{
                            put("version", inter.getVersion());
                            put("community", inter.getCommunity());
                            put("bulk", inter.getBulk());
                        }});
                    }
                }});
                //主机所属的主机组
                List<Map<String, String>> groupIds = new ArrayList<>();
                Map<String, String> group = new HashMap<>();
                group.put("groupid", "2");
                groupIds.add(group);
                put("groups", groupIds);
                List<Map<String, String>> templatesIds = new ArrayList<>();
                Map<String, String> template = new HashMap<>();
//                Map<String, String> templateMysql = new HashMap<>();
                if(1 == inter.getType()){
                    //主机所属的模板
                    //判断主机的系统 1：linux 2：windows
                    if (systemType.equals("1")) {
                        template.put("templateid", "10001");
//                        templateMysql.put("templateid", "10170");
                    }else {
                        template.put("templateid", "10081");
//                        JSONArray temp = (JSONArray) getTemplate(token,"Template App MySQL").get("result");
//                        String templatedid = temp.getJSONObject(0).getString("templateid");
//                        templateMysql.put("templateid", templatedid);
                    }
                    templatesIds.add(template);
//                    templatesIds.add(templateMysql);
                    put("templates", templatesIds);
                }else{
                    //主机所属的模板
                    template.put("templateid", "10229");
                    templatesIds.add(template);
                    put("templates", templatesIds);
                }
//                if(2 == inter.getType()){
//                    //主机所属的模板
//                    template.put("templateid", "10229");
//                    templatesIds.add(template);
//                    put("templates", template);
//                }
//                if(3 == inter.getType()){
//                    //主机所属的模板
//                    template.put("templateid", "10204");
//                    templatesIds.add(template);
//                    put("templates", template);
//                }
//                if(4 == inter.getType()){
//                    //主机所属的模板
//                    template.put("templateid", "10204");
//                    templatesIds.add(template);
//                    put("templates", template);
//                }
                put("inventory_mode", 1);
                put("inventory",new HashMap<String,Object>(){{
                       put("alias",inventory.get("hostType"));
                       put("hardware",inventory.get("cpuType"));
                       put("hardware_full",inventory.get("memory"));
                    if(1 == inter.getType()){
                        put("notes","agent");
                    }else if(2 == inter.getType()){
                        put("notes","switch");
                    }else if(3 == inter.getType()){
                        put("notes","firewall");
                    }else if(4 == inter.getType()){
                        put("notes","single_gate");
                    }
                }});
            }});
        }};
        // 请求发送
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        Map<String, Object> result = new HashMap<String, Object>();
        if (responseMap.get("result") != null) {
            result.put("result", (Map<String, Object>) responseMap.get("result"));
        } else {
            result.put("error", ((Map<String, Object>) responseMap.get("error")).get("data"));
        }
        return result;
    }

    /**
     * 依据模板名称返回模板id，以及关联的主机名称
     * @param token
     * @param templateName
     * @return
     */
    @Override
    public Map<String, Object> getTemplate(String token, String templateName) {
        List<String> TemplateList = new ArrayList<>();
        TemplateList.add(templateName);
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "template.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                put("output", "templatedid");
                put("filter", new HashMap<String, Object>() {{
                    put("host", TemplateList);
                }});
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return responseMap;
    }


    /**
     * 封装创建主机是使用的参数列表（主机组id参数列表和模板参数列表）
     * @param paramType
     * @param params
     * @return
     */
    public List<HashMap<String, String>> makeCreateHostNeededParams(final String paramType, final List<String> params) {
        String addType = "groupid";
        if (!paramType.equals("groups"))
            addType = "templateid";
        List<HashMap<String, String>> groupIdsParam = new ArrayList<>();
        for (String param : params) {
            HashMap<String, String> map = new HashMap<>();
            map.put(addType, param);
            groupIdsParam.add(map);
        }
        return groupIdsParam;
    }

    /**
     * 依据主机hostid删除主机
     * @param token 令牌
     * @param hostid 主机id
     * @return
     */
    @Override
    public Map<String, Object> deleteHost(final String token, final String hostid) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.delete");
            put("id", 1);
            put("auth", token);
            List<String> list = new ArrayList<String>();
            list.add(hostid);
            put("params", list);
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return responseMap;
    }

    /**
     * 查询获取主机状态参数
     * @param token 令牌
     * @param host 主机名称
     * @return
     */
    public List<Map<String, Object>> getHostStatusById(final String token, final String host) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 2);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                List<String> output = new ArrayList<>();
                output.add("status");
                output.add("available");
                output.add("snmp_available");
                output.add("description");
                put("output", output);
                put("filter", new HashMap<String, Object>() {{
                    put("host", host);
                }});
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> result = (List<Map<String, Object>>) responseMap.get("result");
        return result;
    }

    /**
     * 重载-同时查询多个主机,且根据主机hostid查询
     *             (获取主机目前运行状态信息)
     * @param hostids
     * @return
     */
    public List<Map<String, Object>> getHostStatusById(List<String> hostids) {
        // 获取令牌
        String token = APIUtils.getToken();

        // 数据过滤
        List<String> output = new ArrayList<>();
        output.add("status");
        output.add("available");
        output.add("snmp_available");
        output.add("host");

        // 参数封装
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 2);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                put("output", output);
                put("hostids", hostids);
            }});
        }};

        // 数据请求
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> result = (List<Map<String, Object>>) responseMap.get("result");
        return result;
    }

    /**
     * 获取某个主机所属的所有主机组信息
     * @param token
     * @param hostName
     * @return
     */
    public List<Map<String, Object>> getHostGroups(final String token, final String hostName) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 2);
            put("auth", token);

            put("params", new HashMap<String, Object>() {{
                List<String> output = new ArrayList<>();
                output.add("hostid");
                put("output", output);
                put("selectGroups", "extend");
                put("filter", new HashMap<String, Object>() {{
                    List<String> host = new ArrayList<>();
                    host.add(hostName);
                    put("host", host);
                }});
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>) responseMap.get("result");
    }

    /**
     * 获取某个主机关联的所有模板信息
     * @param token
     * @param hostId
     * @return
     */
    public List<Map<String, Object>> getHostTemplates(final String token, final String hostId) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 1);
            put("auth", token);

            put("params", new HashMap<String, Object>() {{
                List<String> output = new ArrayList<>();
                output.add("hostid");
                List<String> selectParentTemplates = new ArrayList<>();
                selectParentTemplates.add("templateid");
                selectParentTemplates.add("name");
                put("output", output);
                put("selectParentTemplates", selectParentTemplates);
                put("hostids", hostId);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>) responseMap.get("result");
    }

    /**
     * 获取某个主机使用接口的所有数据
     * @param token
     * @param hostId
     * @return
     */
    public Map<String, Object> getHostInterfaces(final String token, final String hostId) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "hostinterface.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                put("output", "extend");
                put("hostids", hostId);
            }});

        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return responseMap;
    }
    //删除主机模板(主机更新需要使用)

    /**
     * @param hostid       主机id
     * @param oldTemplates 只含有模板id（templateid）的list集合
     * @return
     */
    public Map<String, Object> deleteHostTemp(final String token, final String hostid, final List<Map<String, Object>> oldTemplates) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.update");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                put("hostid", hostid);
                put("templates_clear", oldTemplates);
            }});
        }};
        //得到结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (Map<String, Object>) responseMap.get("result");
    }

    /**
     * 更新主机
     * @param token 令牌
     * @param hostid 主机id
     * @param host 主机名称
     * @param inter 主机接口
     * @param description 主机描述信息
     * @return
     */
    public Map<String, Object> updateHost(final String token, final String hostid, final String host, final Interface inter, final String description) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.update");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                //主机id，根据主机id来查找需要修改的id
                put("hostid", hostid);
                //修改后主机名称
                put("host", host);
                //获取该主机所有信息（返回的List中只有一个Map）
                Map<String, Object> hostInfo = getHostByHostid(token, hostid).get(0);
                put("description", description);
                //获取该主机所有的接口
                List<Map<String, Object>> interfaces = (List<Map<String, Object>>) hostInfo.get("interfaces");
                //主机修改后的模板信息
                //修改主机的接口（修改主机接口需要获取主机的interfaceid）
                inter.setInterfaceid((String) interfaces.get(0).get("interfaceid"));
                updateInterface(token, inter);
            }});
        }};
        //获取结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        Map<String, Object> result = new HashMap<String, Object>();
        if (responseMap.get("result") != null) {
            result.put("result", (Map<String, Object>) responseMap.get("result"));
        } else {
            result.put("error", ((Map<String, Object>) responseMap.get("error")).get("data"));
        }
        return result;
    }

    /**
     * 删除主机接口
     * @param token
     * @param interfaces
     * @return
     */
    public Map<String, Object> deleteInterface(final String token, final List<Map<String, Object>> interfaces) {
        //获取主机中所有的interfaceid
        List<String> interfaceids = new ArrayList<String>();
        if (interfaces != null) {
            for (Map<String, Object> map : interfaces) {
                interfaceids.add((String) map.get("interfaceid"));
            }
        }
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "hostinterface.delete");
            put("id", 1);
            put("auth", token);
            put("params", interfaceids);
        }};
        //得到结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (Map<String, Object>) responseMap.get("result");
    }

    /**
     * 修改主机接口
     * @param token
     * @param inter
     * @return
     */
    public Map<String, Object> updateInterface(final String token, final Interface inter) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "hostinterface.update");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                put("interfaceid", inter.getInterfaceid());
                put("type", inter.getType());
                put("main", inter.getMain());
                put("useip", inter.getUseip());
                put("ip", inter.getIp());
                put("dns", inter.getDns());
                put("port", inter.getPort());
                if (2 == inter.getType()) {
                    put("details", new HashMap<String, Object>() {{
                        put("version", inter.getVersion());
                        put("community", inter.getCommunity());
                        put("bulk", inter.getBulk());
                    }});
                }
            }});
        }};
        //得到结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return responseMap;
    }

    /**
     * @Description //创建模板
     * @Date 22:18 2020/12/24
     * @Param [groupid, templateName, description]
     **/
    @Override
    public String createTemplate(int groupid, String templateName, String description) {
        String token = APIUtils.getToken();
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("auth", token);
            put("jsonrpc", "2.0");
            put("method", "template.create");
            put("id", 1);
            put("params", new HashMap<String, Object>() {{
                put("groups", new HashMap<String, Object>() {{
                    put("groupid", groupid);
                }});
                put("host", templateName);
                put("description", description);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        Map<String, Object> result = (Map<String, Object>) responseMap.get("result");
        if (result != null) {
            List<String> templateids = (List<String>) result.get("templateids");
            return templateids.get(0);
        }
        return null;
    }

    /**
     * 根据主机id查询自动发现规则
     * @param token
     * @param hostid
     * @param systemType
     * @return
     */
    public List<Map<String, Object>> getDRulesByHostid(final String token, final String hostid, final String systemType){
        List<String> rulesName = new ArrayList<>();
        if (systemType.equals("1")){
            rulesName.add("Mounted filesystem discovery");
        }else if(systemType.equals("2")) {
            rulesName.add("Windows services discovery");
            rulesName.add("Mounted filesystem discovery");
        }
//        }else{
//            rulesName.add("MPU Discovery");
//            rulesName.add("FAN Discovery");
//            rulesName.add("EtherLike-MIB Discovery");
//            rulesName.add("Entity Discovery");
//        }
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "discoveryrule.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("hostids", hostid);
//                put("output", "extend");
                put("filter", new HashMap<String, Object>(){{
                    put("name",rulesName);
                }});
            }});
        }};
        //得到结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>)responseMap.get("result");
    }

    /**
     * 根据主机id禁用自动发现规则
     * @param token
     * @param dRules
     * @return
     */
    public Map<String, Object> deleteDRulesByItemid(final String token, final String[] dRules){
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "discoveryrule.update");
            put("id", 1);
            put("auth", token);
            List<Map<String, Object>> itemList = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < dRules.length; i++){
                Map<String, Object> item = new HashMap<String, Object>();
                item.put("itemid", dRules[i]);
                item.put("status", 1);
                itemList.add(item);
            }
            put("params", itemList);
        }};
        //得到结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (Map<String, Object>)responseMap.get("result");
    }

    /**
     * 根据主机hostid获取用户名及密码
     * @param hostId 主机hostid(String)-Not Null
     * @return
     */
    @Override
    public Host getUserInfoById(String hostId) {
        Host hostInfo = hostMapper.getUserInfoById(hostId);
        return hostInfo;
    }

    /**
     * 添加主机用户名和密码
     * @param host
     */
    @Override
    public void insertHostInfo(Host host) {
        hostMapper.insertHostInfo(host);
    }

    /**
     * 根据hostid修改用户名和密码
     * @param hostInfo
     * @return
     */
    @Override
    public int updateHostInfo(Host hostInfo) {
        // 判断是否存在
        Host host = hostMapper.getUserInfoById(hostInfo.getHostId());

        // 存在则更新，否则插入
        int flag = 0;
        if(host != null){
            flag = hostMapper.updateHostInfo(hostInfo);
        }else{
            flag = hostMapper.insertHostInfo(hostInfo);
        }
        return flag;
    }

    /**
     * 查询SNMP的自动发现规则
     * @param token
     * @param templateId
     * @return
     */
    public List<Map<String, Object>> getDRulesByTemplateid(final String token,final String templateId){
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "discoveryrule.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("templateids", templateId);
                put("output", "extend");
            }});
        }};
        //得到结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>)responseMap.get("result");
    }

    /**
     * 根据tempalteid开启自动发现规则
     * @param token
     * @param dRules
     * @return
     */
    public Map<String, Object> activeDRulesByTemplateid(final String token, final String[] dRules){
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "discoveryrule.update");
            put("id", 1);
            put("auth", token);
            List<Map<String, Object>> itemList = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < dRules.length; i++){
                Map<String, Object> item = new HashMap<String, Object>();
                item.put("itemid", dRules[i]);
                item.put("status", 0);
                itemList.add(item);
            }
            put("params", itemList);
        }};
        //得到结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (Map<String, Object>)responseMap.get("result");
    }

    /**
     * 立即执行发现规则
     * @param token
     * @param dRules
     * @return
     */
    public Map<String, Object> DRulesChecknow(final String token, final String[] dRules){
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "discoveryrule.update");
            put("id", 1);
            put("auth", token);
//            List<String> list = new ArrayList<String>();
//            for (String rule : dRules){
//                list.add(rule);
//            }
            List<Map<String, Object>> itemList = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < dRules.length; i++){
                Map<String, Object> item = new HashMap<String, Object>();
                item.put("itemid", dRules[i]);
                item.put("delay", "1s");
                itemList.add(item);
            }
            put("params", itemList);
        }};
        //得到结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
//        System.out.println(responseMap);
        return (Map<String, Object>)responseMap.get("result");
    }

    /**
     * 改为最原始的延时状态：1h
     * @param token
     * @param dRules
     * @return
     */
    public Map<String, Object> DRulesReset(final String token, final String[] dRules){
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "discoveryrule.update");
            put("id", 1);
            put("auth", token);
//            List<String> list = new ArrayList<String>();
//            for (String rule : dRules){
//                list.add(rule);
//            }
            List<Map<String, Object>> itemList = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < dRules.length; i++){
                Map<String, Object> item = new HashMap<String, Object>();
                item.put("itemid", dRules[i]);
                item.put("delay", "1h");
                itemList.add(item);
            }
            put("params", itemList);
        }};
        //得到结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
//        System.out.println(responseMap);
        return (Map<String, Object>)responseMap.get("result");
    }

    /**
     * 根据主机id查询已开启的自动发现规则
     * @param token
     * @param hostid
     * @param systemType
     * @return
     */
    public List<Map<String, Object>> getActiveDRulesByHostid(final String token, final String hostid, final String systemType){
        List<String> rulesName = new ArrayList<>();
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "discoveryrule.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("hostids", hostid);
                put("output", "extend");
            }});
        }};
        if ("2".equals(systemType)){
            rulesName.add("Mounted filesystem discovery");
        }
        //得到结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>)responseMap.get("result");
    }

    /**
     * 根据主机id查询已开启的资产清单
     * @param token
     * @param hostid
     * @return
     */
    public  Map<String, Object> getHostInventory(final String token, final String hostid) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 1);
            put("auth", token);
            ArrayList<String> arr = new ArrayList<String>();
            arr.add(hostid);
            // 筛选需要的资产清单
            ArrayList<String> inv = new ArrayList<String>();
            inv.add("notes");
            put("params", new HashMap<String, Object>() {{
                put("output", arr);
                put("hostids", hostid);
                put("selectInventory", inv);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return responseMap;
    }

    /**
     * 获取所有主机的所有信息
     * @param token
     * @return
     */
    public List<Map<String, Object>> get_all_host_imporant(final String token) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 2);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                List<String> output = new ArrayList<>();
                output.add("hostid");
                output.add("name");
                put("output", output);
                // 过滤掉不可用的主机
                put("filter", new HashMap<String,Object>(){{
                    put("available", 1);
                }});
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>) responseMap.get("result");
    }

    /**
     * 获取所有的snmp指定监控项
     * @param token
     * @return
     */
    @Override
    public List<Map<String, Object>> get_all_snmp_host_imporant(String token) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 2);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                List<String> output = new ArrayList<>();
                output.add("hostid");
                output.add("name");
                put("output", output);
                // 过滤掉不可用的主机
                put("filter", new HashMap<String,Object>(){{
                    put("snmp_available", 1);
                }});
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>) responseMap.get("result");

    }

    /**
     * 根据主机id获得名字和端口和ip
     * @param token
     * @param hostid
     * @return
     */
    public List<Map<String, Object>> get_details_by_hostid(final String token, final String hostid) {
        String[] interfaceProperty = new String[]{"ip","port"};
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 2);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                List<String> output = new ArrayList<>();
                output.add("hostid");
                output.add("name");
                put("hostids",hostid);
                put("output", output);
                put("selectInterfaces",interfaceProperty);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String,Object>>)responseMap.get("result");
    }

    /**
     * 根据主机id获取其主机名称
     * @param hostid 主机id(String)
     * @return
     */
    @Override
    public String get_name_by_hostid(String hostid) {
        String token = APIUtils.getToken();
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 2);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                List<String> output = new ArrayList<>();
                output.add("hostid");
                output.add("name");
                put("hostids",hostid);
                put("output", output);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        JSONArray array = (JSONArray) responseMap.get("result");
        JSONObject obj = (JSONObject) array.get(0);
        return obj.get("name").toString();
    }


    /**
     * 根据主机id查询已开启的自动发现规则
     * @param hostid
     * @return
     */
    public List<Map<String, Object>> getNetDRulesByHostid(final String hostid){
        String token = APIUtils.getToken();
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "discoveryrule.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("hostids", hostid);
                put("output", "extend");
                put("search", new HashMap<String, Object>(){{
                    put("key_", "net.if");
                }});
            }});
        }};
        //得到结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>)responseMap.get("result");
    }

    /**
     * 立即执行发现规则
     * @param dRules
     * @param delayTime
     * @return
     */
    public Map<String, Object> setDRulesDelay(final String[] dRules,final String delayTime){
        String token = APIUtils.getToken();
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "discoveryrule.update");
            put("id", 1);
            put("auth", token);
            List<Map<String, Object>> itemList = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < dRules.length; i++){
                Map<String, Object> item = new HashMap<String, Object>();
                item.put("itemid", dRules[i]);
                item.put("delay", delayTime);
                itemList.add(item);
            }
            put("params", itemList);
        }};
        //得到结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (Map<String, Object>)responseMap.get("result");
    }

    /**
     * 获取所有主机指定监控项接口
     * @param token
     * @param type
     * @param avail
     * @param queryString
     * @return
     */
    @Override
    public List<Map<String, Object>> getFilterAllHosts(String token, String type, String avail, String queryString) {

        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 2);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                List<String> output = new ArrayList<>();
                output.add("hostid");
                output.add("description");
                output.add("host");
                output.add("status");
                output.add("available");
                output.add("snmp_available");
                put("output", output);
                put("filter", new HashMap<String, Object>() {{
                    if (type.equals("1")&& avail.equals("1")){//服务器可用
                        put("available","1");
                    }else if (type.equals("1") && avail.equals("2")){//服务器不可用
                        put("available","2");
                    }else if (type.equals("1") && avail.equals("0") ){//服务器（可用，不可用）
                        put("available", new String[]{"1", "2"});
                    }else if (type.equals("2")  && avail.equals("1")){//网络设备可用
                        put("snmp_available","1");
                    }else if (type.equals("2") && avail.equals("2")){//网络设备不可用
                        put("snmp_available","2");
                    }else if (type.equals("2") && avail.equals("0") ){//网络设备（可用，不可用）
                        put("snmp_available",new String[]{"1","2"});
                    }else if (type.equals("0") && avail.equals("1")){//可用
                        put("available","1");
                        put("snmp_available","1");
                    }else if (type.equals("0") && avail.equals("2") ){//不可用
                        put("available","2");
                        put("snmp_available","2");
                    }else {
                    }
                }});
                put("search", new HashMap<String, Object>() {{
                    put("host",queryString);
                }});
                put("searchByAny",true);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>) responseMap.get("result");
    }

    /**
     * 根据IP查询所有主机
     * @param token
     * @param ip
     * @return
     */
    @Override
    public List<String> getAllHostsByIp(String token, String ip) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "hostinterface.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                List<String> output = new ArrayList<>();
                output.add("hostid");
                put("output", output);
                put("filter", new HashMap<String, Object>() {{
                    put("ip",ip);
                }});
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        JSONArray jsonArray = (JSONArray) responseMap.get("result");
        List filterHostids = new ArrayList();
        for (int i = 0; i < jsonArray.size(); i++) {
            Map<String,Object> curMap = DateUtils.JsonToMap(jsonArray.getJSONObject(i));
            filterHostids.add(curMap.get("hostid"));
        }
        return filterHostids;
    }

    /**
     * 批量返回指定的hostid的主机信息
     * @param token 令牌
     * @param type 主机类型（服务器或网络设备）
     * @param avail 运行状态筛选
     * @param queryFilterHostids 指定的主机hostid（List<String>）
     * @return
     */
    @Override
    public List<Map<String, Object>> getFilterAllHosts_ip(String token, String type, String avail, List<String> queryFilterHostids) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 2);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                // 对于返回的数据进行过滤控制，剔除不必要的数据信息
                List<String> output = new ArrayList<>();
                output.add("hostid");
                output.add("description");
                output.add("host");
                output.add("status");
                output.add("available");
                output.add("snmp_available");
                put("output", output);
                put("hostids",queryFilterHostids); // 返回指定ids的主机
                put("filter", new HashMap<String, Object>() {{
                    if (type.equals("1")&& avail.equals("1")){//服务器可用
                        put("available","1");
                    }else if (type.equals("1") && avail.equals("2")){//服务器不可用
                        put("available","2");
                    }else if (type.equals("1") && avail.equals("0") ){//服务器（可用，不可用）
                        put("available", new String[]{"1", "2"});
                    }else if (type.equals("2")  && avail.equals("1")){//网络设备可用
                        put("snmp_available","1");
                    }else if (type.equals("2") && avail.equals("2")){//网络设备不可用
                        put("snmp_available","2");
                    }else if (type.equals("2") && avail.equals("0") ){//网络设备（可用，不可用）
                        put("snmp_available",new String[]{"1","2"});
                    }else if (type.equals("0") && avail.equals("1")){//可用
                        put("available","1");
                        put("snmp_available","1");
                    }else if (type.equals("0") && avail.equals("2") ){//不可用
                        put("available","2");
                        put("snmp_available","2");
                    }else {
                    }
                }});
                put("searchByAny",true);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (List<Map<String, Object>>) responseMap.get("result");
    }

    /**
     * 根据主机id判断其操作系统类型
     * @param hostid
     * @return flag（0-windows；1-Linux；2-未知）
     */
    @Override
    public int checkSystemType(String hostid) {
        String token = APIUtils.getToken();
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "template.get");
            put("id", 2);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                List<String> output = new ArrayList<>();
                output.add("templateid");
                put("output", output);
                put("hostids",hostid);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        int flag = 2;
        if(responseMap.get("result") != null){
            List<Map<String,String>> result =  (List<Map<String,String>>)responseMap.get("result");
            if("10081".equals(result.get(0).get("templateid"))){
                flag = 0;// windows
            }else if("10001".equals(result.get(0).get("templateid"))){
                flag = 1;// Linux
            }else if ("10229".equals(result.get(0).get("templateid"))){
                flag = 2;// 网络设备
            }
        }
        return flag;
    }

    /**
     * 获取某个主机的各项运行指标,如: 设备名称,设备状态,内存,磁盘,cpu利用率等
     * @param hostid
     * @return
     */
    @Override
    public Map<String, Object> getHostRunDateils(String hostid) {
        // 获取令牌
        String token = APIUtils.getToken();

        // ***获取主机基本信息
        // 信息筛选
        List<String> needData = new ArrayList<>();
        needData.add("host");
        needData.add("hostid");
        needData.add("status");
        needData.add("available");
        needData.add("snmp_available");
        String[] interfaceProperty = new String[]{"ip","port"};
        // 参数封装
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output",needData);
                put("selectInterfaces",interfaceProperty);
                put("hostids",hostid);
            }});
        }};
        // 数据返回并封装
        Map<String,Object> result = new HashMap<>();
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        Map<String,String> host = ((List<Map<String,String>>)responseMap.get("result")).get(0);
        result.put("host_base_inf",host);

        // ***获取主机运行信息
        long totalDiskSpace = 0L;
        long usedDiskSpace = 0L;
        if(host != null){
            // 服务器
            if("0".equals(host.get("snmp_available")) && !"0".equals(host.get("available"))){
                ItemServiceImpl itemServiceImpl = new ItemServiceImpl();
                List<Map<String,Object>> rundateils = itemServiceImpl.get_important_item_byid(hostid, token);
                // cpu和内存利用率可以直接获取,磁盘利用率通过现有数据计算(单位:%)
                for (Map<String, Object> item : rundateils) {
                    // cpu利用率
                    if("CPU utilization".equals(item.get("name"))){
                        result.put("cpu_utilization",item.get("lastvalue").toString());
                    }
                    // 内存利用率
                    if("Memory utilization".equals(item.get("name"))){
                        result.put("memery_utilization",item.get("lastvalue").toString());
                    }
                    // 统计系统各个磁盘使用情况
                    if(((String)item.get("name")).contains("Total space")){
                        totalDiskSpace+=Long.parseLong(item.get("lastvalue").toString());
                    }
                    if(((String)item.get("name")).contains("Used space")){
                        usedDiskSpace+=Long.parseLong(item.get("lastvalue").toString());
                    }
                }
            // 网络设备
            }else{
                MonitorServiceImpl monitorServiceImpl = new MonitorServiceImpl();
                Map<String,Object> resultSnmp = monitorServiceImpl.getSnmpCpuAndMemryByHostid(hostid);
                // getSnmpCpuAndMemryByHostid()中已经做了空判断
                result.put("cpu_utilization",resultSnmp.get("CPUUtilization").toString());
                result.put("memery_utilization",resultSnmp.get("MemoryUtilization").toString());
            }
        }

        if(!result.containsKey("memery_utilization")){
            result.put("memery_utilization","--");
        }
        if(!result.containsKey("cpu_utilization")){
            result.put("cpu_utilization","--");
        }
        // 磁盘利用率
        if(totalDiskSpace == 0L || usedDiskSpace == 0L || (totalDiskSpace < usedDiskSpace)){
            result.put("DiskUtilization", "--");
        }else {
            result.put("DiskUtilization", ((double)usedDiskSpace/(double)totalDiskSpace)*100);
        }

        return result;
    }

    /**
     * 单独获取主机相关参数 数量 count （新添加接口）
     * @return
     */
    @Override
    public Map<String, Object> getHostRunDateils_api() {
        final String token = APIUtils.getToken();

        // 获取主机相关情况 在线 离线 总数
        HashMap<String, Object> recMap = new HashMap<>();

        Map<String, Object> numbersOfHostInDifferentType = dashBoardService.getNumbersOfHostInDifferentType();
        recMap.put("allHostNum", numbersOfHostInDifferentType.get("total"));
        recMap.put("onlineHostNum", numbersOfHostInDifferentType.get("available"));
        recMap.put("offlineHostNum", numbersOfHostInDifferentType.get("unaviNumber"));

        // 查询已处理个数
        Map<String, Object> unHandleEventsMap = getunHandleEvents(token, false);
        Long unHandleProNum = Long.valueOf((String) unHandleEventsMap.get("result"));
        recMap.put("unHandleProNum", unHandleProNum);

        Map<String, Object> handleEventsMap = getHandleEvents(token);
        Long handleProNum = Long.valueOf((String) handleEventsMap.get("result"));
        recMap.put("handleProNum", handleProNum);
        recMap.put("allProNum", unHandleProNum + handleProNum);
        return recMap;
    }

    // 获取已处理告警 总数
    private Map<String, Object> getHandleEvents(String token) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("countOutput", true);
            put("value", 1);    // 1代表历史告警
            //put("acknowledged", true);
        }};

        // 填入参数
        Map<String, Object> parameterMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "event.get");
            put("id", 1);
            put("auth", token);
            put("params", paramsMap);
        }};
        return APIUtils.sendRequest(JSON.toJSONString(parameterMap, SerializerFeature.WriteMapNullValue));
    }

    // 获取未处理告警 总数
    private Map<String, Object> getunHandleEvents(String token, boolean isAck) {
        final Map<String, String> searchMap = new HashMap<String, String>() {{
            put("r_eventid", "0");  // 筛选出尚未解决的问题
        }};

        // 填入params的对应参数
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("countOutput", true);
            put("acknowledged", isAck);     // 筛选未被确认的问题
            put("filter", new HashMap<String, Object>() {{
                put("searchByAny", true);   // 开启筛选
                put("search", searchMap);    // 具体筛选，规则为LIKE "%...%"
                put("startSearch", true);    // 从头开始搜索
            }});
        }};

        // 填入最终参数
        Map<String, Object> parameterMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "problem.get");
            put("id", 1);
            put("auth", token);
            put("params", paramsMap);
        }};

        return APIUtils.sendRequest(JSON.toJSONString(parameterMap, SerializerFeature.WriteMapNullValue));
    }
}
